package main
import (
	"fmt"
	"time"
)

func printer(ch chan string){
	fmt.Println("printer start ...")
	msg := <- ch// 阻阻塞等待接收数据
	fmt.Println("Received",msg)
}


func main(){

	// // 无缓冲通道
	// fmt.Println("Main start ...")
	// noBufCh := make(chan string)
	// go printer(noBufCh)
	// fmt.Println("Sending hello ...")

	// noBufCh <- "hello"	
	// fmt.Println("Sent hello ...")// 这行会在 printer 接收后才打印

	// time.Sleep(time.Millisecond * 100)// 确保 Goroutine 有时间完成


	// 缓冲通道
	fmt.Println("Main start ...")
	bufCh := make(chan string,2)

	go printer(bufCh)

	bufCh <- "hello"	
	bufCh <- "world"

	bufCh <- "hahaha"
	// bufCh <- "hehehe"// 阻塞	

	fmt.Println(<-bufCh)// hello 被协程取走，所以取出来的是world
	fmt.Println(<-bufCh)// hahaha

	time.Sleep(time.Millisecond * 100)// 确保 Goroutine 有时间完成
}